package com.jinyang.plugindemo.service

import android.app.Service
import android.content.Context
import android.content.Intent
import android.os.IBinder
import com.jinyang.plugindemo.log

/**
 * @Author:         LiuJinYang
 * @CreateDate:     2021/12/14
 * @Description:
 */
class StubService : Service() {
    var serviceName: String? = null
    var pluginService: Service? = null

    companion object {
        var pluginClassLoader: ClassLoader? = null
        fun startService(context: Context, classLoader: ClassLoader, serviceName: String) {
            log("StubService.startService")
            pluginClassLoader = classLoader
            val intent = Intent(context, StubService::class.java)
            intent.putExtra("serviceName", serviceName)
            context.startService(intent)
        }

        fun stopService(context: Context, classLoader: ClassLoader, serviceName: String) {
            log("StubService.stopService")
            pluginClassLoader = classLoader
            val intent = Intent(context, StubService::class.java)
            intent.putExtra("serviceName", serviceName)
            context.stopService(intent)
        }
    }

    override fun onCreate() {
        super.onCreate()
        log("StubService.onCreate")
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        log("StubService.onStartCommand")
        val res = super.onStartCommand(intent, flags, startId)
        serviceName = intent?.getStringExtra("serviceName")
        if (pluginService == null) {
            pluginService = pluginClassLoader?.loadClass(serviceName)?.newInstance() as Service
            pluginService?.onCreate()
        }
        return pluginService?.onStartCommand(intent, flags, startId) ?: res
    }

    override fun onDestroy() {
        super.onDestroy()
        log("StubService.onDestroy")
        if (pluginService!=null) {
            pluginService?.onDestroy()
            pluginService = null
        }
    }

    override fun onBind(intent: Intent?): IBinder? {
        log("StubService.onBind")
        return pluginService?.onBind(intent)
    }

    override fun onUnbind(intent: Intent?): Boolean {
        log("StubService.onUnbind")
        return pluginService?.onUnbind(intent) ?: super.onUnbind(intent)
    }
}